package com.ruoyi.wxapp;

import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.util.SignUtils;
import com.ruoyi.app.interceptor.SessionUtil;
import com.ruoyi.cms.domain.CrmMember;
import com.ruoyi.cms.domain.MemberOrder;
import com.ruoyi.cms.service.IMemberOrderService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.wxapp.config.TypeEnum;
import com.ruoyi.wxapp.config.WeChatAppPayProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : Gentle
 * @date : 2019/5/17 12:11
 * @description:
 */
@RestController
public class WeChatAppPayController {

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    WeChatAppPayProperties weChatPayProperties;

   @Autowired
   private IMemberOrderService memberOrderService;


    private final Logger logger = LoggerFactory.getLogger(this.getClass());




    /**
     * 此处处理订单信息，构建订单数据。app支付使用
     *
     * type代表支付类型 2是物业1是房租
     * @return
     */
    @RequestMapping(value = "/app/wxapp/appPay",method = {RequestMethod.GET,RequestMethod.POST})
    public AjaxResult weChatRenewPay(HttpServletRequest request,
                                     Integer type,
                                     String money,
                                     String order_no,
                                     String orderdesc
    ) {

       System.out.println(DateUtils.parseDate(new Date()) + "支付 >>appPay" );
        CrmMember memberInfo =  SessionUtil.getLoginUser();

        //创建续费订单
        MemberOrder memberOrder=new MemberOrder();
        String orderId = IdUtils.getRandomString(32);
        memberOrder.setMemberId(memberInfo.getId());
        memberOrder.setMoney(Long.valueOf(money));
        memberOrder.setOrderCode(orderId);
        memberOrder.setPayStatus(0L);
        memberOrder.setType(type);
        String typeinfo= TypeEnum.getVal(type);
        memberOrder.setContent("支付"+typeinfo+"费用");
        memberOrderService.insertMemberOrder(memberOrder);
        /**
         * 处理内部业务，校验订单等
         */
        final WxPayUnifiedOrderRequest wxPayUnifiedOrderRequest = WxPayUnifiedOrderRequest.newBuilder()
                //调起支付的人的 openId
               // .openid(memberInfo.GET)
                //订单编号
                .outTradeNo(orderId)
                .tradeType(weChatPayProperties.getTradeType())
                //订单金额
                .totalFee(yuanToFee(new BigDecimal(money)))
                //商品描述
                .body(orderdesc)
                //获取本地IP
                .spbillCreateIp(InetAddress.getLoopbackAddress().getHostAddress())
                //回调的 URL 地址
                .notifyUrl(weChatPayProperties.getNotifyUrl())
                .build();
        WxPayUnifiedOrderResult wxPayUnifiedOrderResult =null;
        try {
            wxPayUnifiedOrderResult = wxPayService.unifiedOrder(wxPayUnifiedOrderRequest);
            Map<String, String> param = new HashMap<>();
            param.put("appid", weChatPayProperties.getAppId());
            param.put("partnerid", weChatPayProperties.getMchId());
            param.put("prepayid", wxPayUnifiedOrderResult.getPrepayId());
            param.put("package", "Sign=WXPay");
            String timeStamp = createTimestamp();
            String nonceStr = String.valueOf(System.currentTimeMillis());
            param.put("noncestr",nonceStr);
            param.put("timestamp", System.currentTimeMillis() / 1000 + "");
            String paySign = SignUtils.createSign(param, "MD5", weChatPayProperties.getMchKey(),null);
            param.put("sign", paySign);
            // return returnPayInfoVO;
            return AjaxResult.success(param);
        } catch (WxPayException e) {
            e.printStackTrace();
            throw new RuntimeException("微信支付调起失败！");
        }

       // return AjaxResult.success("ok");
    }


    /**
     * 校验订单
     * @param orderCode
     * @return
     */
    public  Boolean  checkOrder(String orderCode){
        MemberOrder byOrderCode = memberOrderService.findByOrderCode(orderCode);
        if(byOrderCode == null || byOrderCode.getPayStatus().intValue() == 0){
            return false;
        }
        return true;
    }



    /**
     * 1 块钱转为 100 分
     * 元转分
     *
     * @param bigDecimal 钱数目
     * @return 分
     */
    private int yuanToFee(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).intValue();
    }

    /**
     * 时间
     *
     * @return 时间戳
     */
    private String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

}